﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;

namespace ExcelFileQueryTool
{
    class ObjectPropertyComparer<T> : System.Collections.Generic.IComparer<T>
    {
        private PropertyDescriptor property;
        private ListSortDirection direction;

        public ObjectPropertyComparer(PropertyDescriptor property, ListSortDirection direction)
        {
            this.property = property;
            this.direction = direction;
        }

        #region IComparer<T>

        /// <summary>
        /// 比较方法
        /// </summary>
        /// <param name="x">相对属性x</param>
        /// <param name="y">相对属性y</param>
        /// <returns></returns>
        public int Compare(T x, T y)
        {
            int returnValue;

            if (x == null && y == null)
                returnValue = 0;
            else if (x == null)
                returnValue = -1;
            else if (y == null)
                returnValue = 1;
            else
            {
                object xValue = x.GetType().GetProperty(property.Name).GetValue(x, null);
                object yValue = y.GetType().GetProperty(property.Name).GetValue(y, null);

                if (xValue == null && xValue == null)
                    returnValue = 0;
                else if (xValue == null)
                    returnValue = -1;
                else if (yValue == null)
                    returnValue = 1;
                else if (xValue is IComparable)
                    returnValue = ((IComparable)xValue).CompareTo(yValue);
                else if (xValue.Equals(yValue))
                    returnValue = 0;
                else
                    returnValue = xValue.ToString().CompareTo(yValue.ToString());
            }

            if (direction == ListSortDirection.Ascending)
                return returnValue;
            else
                return returnValue * -1;
        }

        public bool Equals(T x, T y)
        {
            if (x == null && y == null)
                return true;

            if (x == null || y == null)
                return false;

            return x.Equals(y);
        }

        public int GetHashCode(T obj)
        {
            if (obj == null)
                return 0;
            else
                return obj.GetHashCode();
        }

        #endregion
    }
}